﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace PerCiGal.Common
{
    public class FunctionImage
    {
        public static Image ImageFromByteArray(byte[] val)
        {
            if (val == null) return null;

            var byteBlobData = (Byte[])val;
            var stmBlobData = new MemoryStream(byteBlobData);
            return Image.FromStream(stmBlobData);
        }

        public static Byte[] ByteArrayFromImage(Image imageToConvert)
        {
            if (imageToConvert != null)
            {
                byte[] ret;

                try
                {
                    using (var ms = new MemoryStream())
                    {
                        imageToConvert.Save(ms, ImageFormat.Jpeg);
                        ret = ms.ToArray();
                    }
                }
                catch (Exception) { throw; }

                return ret;
            }
            else return null;
        }

        public static Byte[] ByteArrayFromImage(Image imageToConvert, ImageFormat imageFormat)
        {
            if (imageToConvert != null)
            {
                byte[] ret;

                try
                {
                    using (var ms = new MemoryStream())
                    {
                        imageToConvert.Save(ms, imageFormat);
                        ret = ms.ToArray();
                    }
                }
                catch (Exception) { throw; }

                return ret;
            }
            else return null;
        }

        public static void ImageToFile(Image imageToSave, string filePath)
        {
            if (imageToSave != null)
            {
                var file = new FileInfo(filePath);

                if (file.Extension.ToLower() == ".jpg")
                {
                    imageToSave.Save(filePath, ImageFormat.Jpeg);
                }
                else if (file.Extension.ToLower() == ".gif")
                {
                    imageToSave.Save(filePath, ImageFormat.Gif);
                }
            }
        }

        public static void ImageToFile(Image imageToSave, string filePath, ImageFormat imageFormat)
        {
            if (imageToSave != null)
            {
                var file = new FileInfo(filePath);

                if (file.Extension.ToLower() == ".jpg")
                {
                    imageToSave.Save(filePath, ImageFormat.Jpeg);
                }
                else if (file.Extension.ToLower() == ".gif")
                {
                    imageToSave.Save(filePath, imageFormat);
                }
            }
        }

        public static Image ImageFromFile(string filePath)
        {
            var img = Image.FromFile(filePath);

            return img;
        }
    }
}
